# send_to_archive.py
from __future__ import with_statement
import time, sys, httplib, urllib, logging
import simplejson as json
import common

READINGS = '/var/www/readings.json'
# READINGS = 'readings.json'

SERVER = 'roqueislandmonitor.appspot.com'
# SERVER = 'localhost:8080'
SERVER = 'grideyeq.com'
PAGE = '/archive'
PAGE = '/data/postReadings.php'
INTERVAL = 60
#INTERVAL = 1

common.setup_logging()

run = True

while run:
    with open(READINGS, 'r') as f:
        l = f.read().encode()
    try:
        readings = json.loads(l)
    except:
        logging.debug('json failure: '+"'"+l+"'")
        readings = {u'datetime': ''}

    #print readings

    if readings[u'datetime'] != '':
        params = urllib.urlencode({'content': l})
        ok = True
        try:
            conn = httplib.HTTPConnection(SERVER)
        except:
            logging.debug('httplib.HTTPConnection failure: '+str(sys.exc_info()))
            ok = False

        headers = {"Content-type": "application/x-www-form-urlencoded",
                   "Accept": "text/plain"}
        if ok:
            try:
                conn.request('POST', PAGE, params, headers)
            except:
                logging.debug('conn.request() failure: '+str(sys.exc_info()))
                ok = False
        if ok:
            resp = conn.getresponse()
            if resp.status != 200:
                #raise Exception(resp.reason)
                logging.debug('resp.status != 200: '+str(resp.status))
                print resp.status
            resp.read()
        conn.close()

    time.sleep(INTERVAL)
    #run = False
